package com.myjoje.util;

import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class OkHttpUtil {
    private static OkHttpClient okHttpClient;

    private OkHttpUtil() {
    }

    public static OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            synchronized (OkHttpUtil.class) {
                if (okHttpClient == null) {
                    okHttpClient = new OkHttpClient.Builder()
                            .connectTimeout(20, TimeUnit.SECONDS)
                            .writeTimeout(20, TimeUnit.SECONDS)
                            .readTimeout(20, TimeUnit.SECONDS)
                            .build();
                }
            }
        }
        return okHttpClient;
    }

    /**
     * get请求
     */
    public static Response get(String url) throws IOException {
        Request request = new Request.Builder().url(url).build();
        return getOkHttpClient().newCall(request).execute();
    }

    public static Response postJson(String url, String json) throws IOException {
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , json);
        return post(url, requestBody);
    }

    public static Response postSoap(String url, String soap) throws IOException {
        RequestBody requestBody = FormBody.create(MediaType.parse("text/xml; charset=utf-8")
                , soap);
        return post(url, requestBody);
    }


    public static Response post(String url, RequestBody requestBody) throws IOException {
        Request request = new Request.Builder().url(url).post(requestBody).build();
        return getOkHttpClient().newCall(request).execute();
    }

}
